<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :title="title4"
      :beforeClose="handleClose4"
      :visible.sync="dialogVisible4"
      width="500px">
      <el-form :model="materialForm" size="mini" label-width="130px" :rules="rules4" ref="materialForm">
        <el-form-item label="客户名称:">
          <el-input v-model="materialForm.customerName" disabled style="width: 300px;"></el-input>
        </el-form-item>

        <el-form-item label="品类:" prop="categoryId">
          <el-cascader
            filterable
            :disabled="cutItem.isOrder == 1"
            ref="category"
            @change="changeCategoryId"
            :options="categoryList" clearable  v-model="materialForm.categoryId" :props="{emitPath:false,value:'categoryId',label:'categoryName'}"></el-cascader>
        </el-form-item>

        <el-form-item label="牌号:" prop="goodsName">
          <el-select
            @change="changeGoodsSn"
            :disabled="cutItem.isOrder == 1"
            v-model="materialForm.goodsName"
            filterable
            placeholder="请选择/输入牌号"
            clearable>
            <el-option
              v-for="(item,index) in goodsList"
              :key="index"
              :label="item.brandName+'/'+item.goodsSn"
              :value="item.categoryId+'/'+item.brandId+'/'+item.goodsSn">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="月使用量">
<!--          <el-input type="number" v-model="materialForm.cycleNumber" clearable style="width: 200px;"></el-input>-->
          <el-cascader :options="numOptions" clearable :show-all-levels="false" v-model="materialForm.cycleNumber" :props="{emitPath:false}"></el-cascader>
        </el-form-item>

        <el-form-item label="采购频率(天/次):">
           <el-input type="number" v-model="materialForm.cycleDays" clearable style="width: 200px;"></el-input>
        </el-form-item>

        <el-form-item label="采购渠道:">
          <el-select v-model="materialForm.supplierName" filterable clearable>
            <el-option v-for="(item,index) in supplierNameList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="采购量级:">
          <el-select v-model="materialForm.purchaseLevel" filterable clearable>
             <el-option v-for="(item,index) in purchaseLevelList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="安全库存">
          <el-input type="number" v-model="materialForm.stock" clearable style="width: 200px;"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer" v-if="materialDialogType!='see'">
          <el-button @click="handleClose4">取 消</el-button>
          <el-button type="primary" @click="handleConfirm4" :loading="btnLoading4">确 定</el-button>
      </span>
      <span slot="footer" class="dialog-footer" v-else>
         <el-button @click="handleClose4">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getCustomerInfoAPI,
  getBrandAndGoodsSn,
  getCategoryList
} from '@/api/company';
import {
  getCustomerSetting,
  orderGoodsList
} from '@/api/partner';
import {editUseGoodsAPI} from '@/api/fms';
const defaultMaterialForm = {
  customerId: '',
  customerName: '',
  ugId: '',//id(编辑用)
  categoryId: '',//产品线id
  goodsSn: '',//牌号
  cycleNumber: '',//月使用量
  cycleDays: '',//频率
  supplierName: '',//采购渠道
  stock: '',//库存
  purchaseLevel:'',//采购量级别

  brandId:'',
  brandName:'',
  sapGoodsNo:'',
  categoryName:'',
  goodsName:''
};
export default {
  name: "addUseGoods",
  data(){
    return {
      materialForm: JSON.parse(JSON.stringify(defaultMaterialForm)),
      title4: '',
      dialogVisible4: false,
      btnLoading4: false,
      materialDialogType: '',
      purchaseLevelList: [],
      supplierNameList:[],
      goodsLineList: [],
      goodsList:[],
      rules4: {
        categoryId: [{
          required: true, message: '请选择品类', trigger: 'change'
        }],
        goodsName: [{
          required: true, message: '请选择厂家牌号', trigger: 'change'
        }],
      },

      cutItem:'',
      numOptions:[],
      categoryList:[]
    }
  },
  filters:{

  },
  created() {
  },
  methods: {
    changeGoodsSn(){
      let i = this.goodsList.findIndex((el)=>{
        return el.categoryId+'/'+el.brandId+'/'+el.goodsSn == this.materialForm.goodsName
      })
      if(i!= -1){
        this.materialForm.goodsSn = this.goodsList[i]['goodsSn']
        this.materialForm.brandId = this.goodsList[i]['brandId']
        this.materialForm.brandName = this.goodsList[i]['brandName']
        this.materialForm.sapGoodsNo = this.goodsList[i]['sapGoodsNo']
        this.materialForm.goodsName = this.materialForm.categoryId+'/'+this.materialForm.brandId+'/'+this.materialForm.goodsSn
      }
    },
    //获取品类列表
    getcategoryListFn(){
      getCategoryList().then((res)=>{
        this.categoryList = res.list
      })
    },
    //切换品类
    changeCategoryId(){
      this.$nextTick(()=>{
        this.materialForm.categoryName = this.$refs['category'].getCheckedNodes()[0] ? this.$refs['category'].getCheckedNodes()[0]['label'] :''
      })
      this.materialForm.goodsSn = ''
      this.materialForm.brandId = ''
      this.materialForm.brandName = ''
      this.materialForm.sapGoodsNo = ''
      this.materialForm.goodsName = ''
      this.getOrderGoodsList();
    },


    // 获取牌号列表
    getOrderGoodsList(){
      if(this.materialForm.categoryId){
        getBrandAndGoodsSn({
          categoryId:this.materialForm.categoryId
        }).then((res)=>{
          this.goodsList = res.list
        })
      }

    },
    // 获取客户信息配置
    getCustomerInfo() {
      getCustomerInfoAPI({tab:4}).then((res) => {
        this.purchaseLevelList=res;
      })
      getCustomerInfoAPI({tab:8}).then((res) => {
        this.supplierNameList=res;
      })
      getCustomerSetting().then((res) => {
        res.forEach((el) => {
          if (el.cdtCode == 'goods_line') {//产品线
            this.goodsLineList = el.data
          }
        });
      })
    },
    //显示编辑/新增产品
    showPop(type, item) {
      this.title4 = type == 'add' ? '新增产品' : type == 'edit' ? '编辑产品' : '查看产品';
      this.materialDialogType = type;
      this.dialogVisible4 = true;
      this.getCustomerInfo();
      this.getcategoryListFn()
      this.numOptions = []
      for(let i=0;i<1000;i=i+100){
        let label = i == 0 ? (i+1)+'-'+(i+99) : i+'-'+(i+99)
        this.numOptions.push({value:i+99,label: label,children: []});
      }
      this.numOptions.push({value:100,label: '1000吨以上'})
      this.numOptions.forEach((el,index)=>{
        if(el.children){
          let max = el.value;
          let min = el.value-99 <= 0  ? 1 : el.value-99
          this.numOptions[index].children = []
          for(let ii=min; ii<=max;ii++){
            this.numOptions[index].children.push({value:ii,label: ii})
          }
        }
      })
      this.cutItem = item
      if (type == 'add') {
        this.materialForm = JSON.parse(JSON.stringify(defaultMaterialForm));
        this.materialForm.customerId = item.customerId;
        this.materialForm.customerName = item.customerName;
      } else {
        for (let key in defaultMaterialForm) {
          this.materialForm[key]= item[key]? item[key]: defaultMaterialForm[key]
        }
        this.materialForm.goodsName = this.materialForm.categoryId+'/'+this.materialForm.brandId+'/'+this.materialForm.goodsSn
        this.getOrderGoodsList();
      }
    },
    //关闭客户使用材料
    handleClose4() {
      this.$refs.materialForm.clearValidate();
      this.dialogVisible4 = false;
      this.btnLoading4 = false;
    },
    //提交客户使用材料
    handleConfirm4() {
      this.$refs.materialForm.validate((valid) => {
        if (valid) {
          this.btnLoading4 = true;
          editUseGoodsAPI(this.materialForm).then(() => {
            this.btnLoading4 = false;
            this.$message.success('操作成功')
            this.handleClose4();
            this.$emit('update')
          }).catch(() => {
            this.btnLoading4 = false;
          })
        }
      });
    },
  }
};
</script>

<style scoped lang="scss">

</style>
